package cn.schoolwow.flow.monitor.module.common.flow;

import cn.schoolwow.ams.module.block.listBlock.common.domain.remoteSelect.RemoteSelectOption;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.instanceList.QueryInstanceList;

import java.util.ArrayList;
import java.util.List;

public class GetRemoteSelectOptionListCommonFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        List list = flowContext.getData("list", List.class);
        String fieldName = flowContext.getData("fieldName", String.class, "categoryName");

        if(null==list||list.isEmpty()){
            flowContext.putReturnData("remoteSelectOptionList", new ArrayList<>());
            flowContext.brokenCurrentFlow("列表为空");
        }
        List<RemoteSelectOption> remoteSelectOptionList = new ArrayList<>();

        List<String> typeList = QueryInstanceList.newQuery(list)
                .distinct()
                .execute()
                .getSingleFieldValueList(fieldName);
        for(String type:typeList){
            String[] tokens = type.split("-", -1);
            RemoteSelectOption remoteSelectOption = null;
            for(String token:tokens){
                if(null==remoteSelectOption){
                    remoteSelectOption = QueryInstanceList.newQuery(remoteSelectOptionList)
                            .addQuery("label", token)
                            .execute()
                            .getOne();
                    if(null==remoteSelectOption){
                        remoteSelectOption = new RemoteSelectOption(token, token);
                        remoteSelectOptionList.add(remoteSelectOption);
                    }
                }else{
                    if(null==remoteSelectOption.children){
                        remoteSelectOption.children = new ArrayList<>();
                    }
                    RemoteSelectOption queryRemoteSelectOption = QueryInstanceList.newQuery(remoteSelectOption.children)
                            .addQuery("label", token)
                            .execute()
                            .getOne();
                    if(null==queryRemoteSelectOption){
                        RemoteSelectOption childRemoteSelectOption = new RemoteSelectOption(token, token);
                        remoteSelectOption.children.add(childRemoteSelectOption);
                        remoteSelectOption = childRemoteSelectOption;
                    }else{
                        remoteSelectOption = queryRemoteSelectOption;
                    }
                }
            }
        }
        flowContext.putReturnData("remoteSelectOptionList", remoteSelectOptionList);
    }

    @Override
    public String name() {
        return "获取流程类型远程下拉框列表";
    }
}
